package com.net;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;



public class UDPSocketThread implements Runnable {

    String mIpV4 = null;
    int mPort;
    Thread mThread = null;
    EventLoopGroup mEventLoopGroup = null;
    Bootstrap mBootSrap = null;


    public UDPSocketThread(String ipV4, int port){
        if(InitUdpServer(ipV4,port)){
            mThread = new Thread(this);
        }
    }

    public boolean Start(){
        if(this.mThread == null){
            return false;
        }
        if(this.mThread.isAlive()){
            return false;
        }

        this.mThread.start();
        return true;
    }

    public boolean Stop(){
        if(this.mThread == null){
            return false;
        }
        if(!this.mThread.isAlive()){
            return false;
        }

        this.mThread.interrupt();
        return true;
    }

    public boolean Sleep(long millis){
        if(this.mThread == null){
            return false;
        }

        if(!this.mThread.isAlive()){
            return false;
        }

        boolean hasError = false;
        try{
            this.mThread.sleep(millis);
            hasError = true;
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }

        if(hasError){
            return false;
        }

        return true;
    }

    private boolean InitUdpServer(String ipV4, int port){
        if(ipV4 == null || ipV4 == ""){
            return false;
        }
        if(port < 1024 || port > 65535){
            return false;
        }

        this.mIpV4 = ipV4;
        this.mPort = port;
        this.mEventLoopGroup = new NioEventLoopGroup();
        this.mBootSrap = new Bootstrap();

        return true;
    }

    @Override
    public void run() {
        try {
            mBootSrap.group(this.mEventLoopGroup)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST,true)
                    .handler(new UdpServerHandler());
            mBootSrap.bind(this.mIpV4,this.mPort).sync().channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.mEventLoopGroup.shutdownGracefully();
        }
    }
}
